package com.example.config;

import com.example.DTO.UserDTO;
import com.example.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里判断用户是否已经登录
        Object user = request.getSession().getAttribute("user");
        if (user == null) {
            // 用户未登录，返回需要登录的信息
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"请先登录!\"}");
            log.debug("请您先登录！");
            return false;
        }
        //存在，保存信息到ThreadLocal中
        UserHolder.saveUser((UserDTO) user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //视图渲染完成后执行该方法，一次请求获取一次用户信息，用完立即释放
        UserHolder.removeUser();
    }
}
